<?php

function lookup($string){

	$string = str_replace (" ", "+", urlencode($string));
	$details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $details_url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$response = json_decode(curl_exec($ch), true);

	// If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
	if ($response['status'] != 'OK') {
		return null;
	}
	$geometry = $response['results'][0]['geometry'];

	$array = array(
			'latitude' => $geometry['location']['lat'],
			'longitude' => $geometry['location']['lng'],
	);
	return $array;
}

include("../rest/database.php");
include("../rest/database_info.php");


$list = doGetListResult("SELECT refno AS id, fn1 AS name, str AS street, zip, city FROM busiquest WHERE res4 IS NULL OR res4 = '' OR res5 IS NULL OR res5 = '' ");

foreach ($list as $key => $entry) {
	$id = $entry->id; // is this the ID?
	$address = $entry->street.", ".$entry->zip." ".$entry->city;
	$lookup = lookup($address);
	if ($lookup == null) {
		echo "<b>".$entry->name.": $address NOT FOUND!!!</b></br>";
		continue;
	}
	echo $entry->name.": $address -> ".$lookup["latitude"].",".$lookup["longitude"]." </br>";

	// are res4 and ref5 ok?
	createQuery("UPDATE busiquest SET res4 = '".$lookup["latitude"]."', res5 = '".$lookup["longitude"]."' WHERE refno = '$id'");
}

echo "<br><i>Finished.</i>";
?>